<template>
  <div class="about">
    <div class="about-input">
      <div>
        <canvas id="canvas" />
        <!-- <img src="@/assets/cnki.png" style="width: 180px" /> -->
        <div
          style="
            font-size: 14px;
            color: #ffffff;
            text-align: center;
            width: 100%;
          "
        >
          微信扫一扫 手机秒变扫码枪
        </div>
      </div>
      <div
        style="
          margin-left: 40px;
          color: #ffffff;
          font-size: 14px;
          margin-top: 30px;
        "
      >
        <div class="flex-row">
          <div class="flex-row">
            <div>所属部门</div>
            <div style="margin-left: 10px">
              <el-select
                style="width: 220px"
                v-model="dept"
                placeholder="请选择所属部门"
                size="small"
                @change="changeDept"
              >
                <el-option
                  v-for="item in deptList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="flex-row" style="margin-left: 75px">
            <div>是否显示销方名称</div>
            <div style="margin-left: 10px">
              <el-select
                style="width: 220px"
                v-model="mc2Type"
                placeholder="请选择"
                size="small"
                @change="getCode"
              >
                <el-option
                  v-for="item in mcList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="flex-row" style="margin-top: 30px">
          <div class="flex-row" style="margin-left: 10px">
            <div>报销人</div>
            <div style="margin-left: 10px">
              <el-select
                style="width: 220px"
                v-model="user"
                placeholder="请选择报销人"
                size="small"
                @change="getCode"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </div>
            <div style="margin-left: 10px">
              <el-button type="success" size="small" @click="showUser"
                >添加</el-button
              >
            </div>
          </div>
          <div class="flex-row" style="margin-left: 70px">
            <div>报销类型</div>
            <div style="margin-left: 10px">
              <el-select
                style="width: 220px"
                v-model="inType"
                placeholder="请选择报销人"
                size="small"
                @change="changeType"
              >
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
            <div style="margin-left: 10px">
              <el-button type="success" size="small" @click="showType"
                >添加</el-button
              >
            </div>
          </div>
        </div>
      </div>
      <div style="position: absolute; top: 30px; right: 30px">
        <el-button
          v-if="type === 1"
          type="success"
          size="small"
          @click="type = 2"
          >手动录入</el-button
        >
        <el-button
          v-if="type === 2"
          type="success"
          size="small"
          @click="switchType"
          >扫描录入</el-button
        >
      </div>
    </div>
    <div class="scale" v-if="type === 1">
      <div style="display: flex; align-items: center; font-weight: 600">
        <div>本次共核销发票</div>
        <div
          style="
            color: #ff411f;
            font-size: 25px;
            font-weight: 600;
            margin: 0 20px;
          "
        >
          {{ num }}
        </div>
        <div>张</div>
      </div>
      <div class="about-atatus">
        <!-- <el-input
          v-model="scanCode"
          ref="inputValue"
          @blur="inputblur()"
          @keyup.native="concludeData"
        ></el-input> -->
        <input
          class="input-con"
          type="password"
          autocomplete="new-password"
          @blur="inputblur()"
          v-model.lazy="scanCode"
          @keyup.enter="concludeData"
          ref="inputValue"
        />
        <div
          v-if="status === 3 || status === 4"
          style="
            display: flex;
            align-items: center;
            font-size: 16px;
            font-weight: 400;
            color: #333333;
            position: absolute;
            top: 3.2vw;
          "
        >
          <div>核销日期：{{ nowData }}</div>
          <div style="margin-left: 20px">核销人：{{ user }}</div>
        </div>
        <div v-if="status === 1" class="flex-row" style="margin-top: 6vw">
          <img src="@/assets/wait.png" style="width: 45px" />
          <div
            style="
              color: #24d59c;
              font-weight: 600;
              font-size: 39px;
              margin-left: 10px;
            "
          >
            等待扫描发票
          </div>
        </div>
        <div v-if="status === 2" class="flex-row" style="margin-top: 6vw">
          <img src="@/assets/wait.png" style="width: 45px" />
          <div
            style="
              color: #24d59c;
              font-weight: 600;
              font-size: 39px;
              margin-left: 10px;
            "
          >
            发票核销中
          </div>
        </div>
        <div v-if="status === 3" class="flex-row" style="margin-top: 6vw">
          <img src="@/assets/success.png" style="width: 45px" />
          <div
            style="
              color: #24d59c;
              font-weight: 600;
              font-size: 39px;
              margin-left: 10px;
            "
          >
            成功核销
          </div>
        </div>
        <div v-if="status === 4" class="flex-row" style="margin-top: 6vw">
          <img src="@/assets/warn.png" style="width: 45px" />
          <div
            style="
              color: #ff2916;
              font-weight: 600;
              font-size: 39px;
              margin-left: 10px;
            "
          >
            警惕！该发票已核销过！
          </div>
        </div>
        <div style="color: #999999; font-size: 14px; margin-top: 40px">
          {{ text }}
        </div>
      </div>
    </div>
    <div class="scale" v-if="type === 2">
      <div style="display: flex; align-items: center; font-weight: 600">
        <div>本次共核销发票</div>
        <div
          style="
            color: #ff411f;
            font-size: 25px;
            font-weight: 600;
            margin: 0 20px;
          "
        >
          {{ num }}
        </div>
        <div>张</div>
      </div>
      <div class="about-fp">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="发票类型" prop="type">
                <el-select
                  v-model="form.type"
                  style="width: 100%"
                  placeholder="请选择报销类型"
                >
                  <el-option
                    v-for="item in tabList"
                    :key="item.value"
                    :label="item.name"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票日期" prop="kprq">
                <el-date-picker
                  style="width: 100%"
                  v-model="form.kprq"
                  type="date"
                  placeholder="选择开票日期"
                  value-format="yyyyMMdd"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="发票号码" prop="fphm">
                <el-input
                  v-model="form.fphm"
                  placeholder="请输入发票号码"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发票代码" prop="fpdm">
                <el-input
                  v-model="form.fpdm"
                  placeholder="请输入发票代码"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="开票金额" prop="hjje">
                <el-input
                  v-model="form.hjje"
                  placeholder="请输入开票金额"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="sub-but">
          <el-button style="width: 200px" type="primary" @click="submitAll"
            >立即报销</el-button
          >
        </div>
      </div>
    </div>
    <el-dialog
      title="添加报销人"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="userform"
        :model="userform"
        :rules="userrules"
        label-width="100px"
      >
        <el-form-item label="报销人" prop="name">
          <el-input v-model="userform.name" placeholder="请输入报销人" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-select
            style="width: 100%"
            v-model="userform.deptId"
            clearable
            placeholder="请选择所属部门"
          >
            <el-option
              v-for="item in deptList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报销类型 -->
    <el-dialog
      title="添加报销类型"
      :visible.sync="typeShow"
      width="500px"
      append-to-body
    >
      <el-form
        ref="typeform"
        :model="typeform"
        :rules="typerules"
        label-width="80px"
      >
        <el-form-item label="报销类型" prop="name">
          <el-input v-model="typeform.name" placeholder="请输入报销类型" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitType">确 定</el-button>
        <el-button @click="typeShow = flase">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listAllInvoiceDept } from "@/api/business/invoiceDept";
import {
  listAllInvoiceExpensesUser,
  addInvoiceExpensesUser,
  checkUser,
} from "@/api/business/invoiceExpensesUser";
import {
  listAllInvoiceExpensesType,
  addInvoiceExpensesType,
} from "@/api/business/invoiceExpensesType";
import { getToken } from "@/utils/auth";
import QRCode from "qrcode";
export default {
  data() {
    return {
      nowData: "",
      status: 1,
      text: "",
      scanCode: "",
      num: 0,
      open: false,
      userform: {
        name: null,
        deptId: null,
      },
      userrules: {
        name: [{ required: true, message: "报销人不能为空", trigger: "blur" }],
        deptId: [
          { required: true, message: "所属部门不能为空", trigger: "change" },
        ],
      },
      typeShow: false,
      typeform: {
        name: null,
      },
      typerules: {
        name: [
          { required: true, message: "报销类型不能为空", trigger: "blur" },
        ],
      },
      selectId: null,
      queryParams: {
        deptId: null,
        parentDeptId: null,
      },
      user: "",
      userList: [],
      dept: null,
      deptList: [],
      inType: "",
      typeList: [],
      mc2Type: 0,
      mcList: [
        { name: "否", value: 0 },
        { name: "是", value: 1 },
      ],
      tabList: [
        { name: "专用发票", value: "01" },
        { name: "普通发票", value: "02" },
      ],
      form: {
        type: null,
        fphm: null,
        hjje: null,
        kprq: null,
        fpdm: null,
        bxlx: "",
        bxr: "",
        mc2: "",
        deptId: null,
      },
      type: 1,
      value: "",
      rules: {
        type: [
          { required: true, message: "请输入发票类型", trigger: "change" },
        ],
        kprq: [
          { required: true, message: "请输入开票日期", trigger: "change" },
        ],
        fphm: [{ required: true, message: "请输入发票号码", trigger: "blur" }],
        hjje: [{ required: true, message: "请输入开票金额", trigger: "blur" }],
      },
      isLog: false,
      phoneToken: "",
      phoneName: "",
      phoneCode: "",
      phoneType: "",
    };
  },
  created() {
    this.phoneToken = getToken();
    this.phoneName = JSON.parse(localStorage.getItem("selectCompany")).deptName;
    this.phoneCode = JSON.parse(
      localStorage.getItem("selectCompany")
    ).taxpayerNum;
    this.selectId = JSON.parse(localStorage.getItem("selectCompany")).deptId;
    this.queryParams.parentDeptId = this.selectId;
    this.nowData = this.GetDateStr(0);
    // this.getList();
    this.getAllList();
    // this.getType();
  },

  mounted() {
    this.$nextTick(() => {
      this.$refs.inputValue.focus();
    });

    this.getCode();
    // let str = "01,32,,24332000000023291591,367.25,20240124,,DC98";
    // console.log(str.split(","));
  },
  methods: {
    switchType() {
      this.type = 1;
      this.$nextTick(() => {
        this.$refs.inputValue.focus();
      });
    },
    concludeData(e) {
      if (this.scanCode && !this.isLog) {
        console.log(this.scanCode);
        this.isLog = true;
        const decodeText = this.scanCode;
        this.scanCode = "";
        console.log(decodeText.split(","));
        if (decodeText.split(",").length < 7) {
          this.$modal.msgError("请扫描发票二维码");
          this.isLog = false;
          return;
        }

        let fphm;
        let hjje;
        let fpdm = "";
        let jym = "";
        let kprq = "";
        let type = "02";
        if (
          decodeText.split(",")[2] === "" ||
          decodeText.split(",")[2] === " "
        ) {
          fphm = decodeText.split(",")[3];
          hjje = decodeText.split(",")[4];
          kprq = decodeText.split(",")[5];
        } else {
          kprq = decodeText.split(",")[5];
          fpdm = decodeText.split(",")[2];
          fphm = decodeText.split(",")[3];
          hjje = decodeText.split(",")[4];
          jym = decodeText.split(",")[6];
          type = "01";
        }
        console.log(fphm);
        this.goDetai(fphm, hjje, fpdm, jym, kprq, type);
        console.log(222);
      }
    },
    async goDetai(fphm, hjje, fpdm, jym, kprq, type) {
      try {
        this.status = 2;
        const res = await checkUser({
          type,
          kprq,
          jym,
          fpdm,
          fphm,
          hjje,
          bxlx: this.inType,
          bxr: this.user,
          mc2Type: this.mc2Type,
          deptId: this.selectId,
        });
        this.status = 3;
        this.text = `最近核销：${fphm}`;
        this.num++;
        this.isLog = false;
      } catch (e) {
        console.log(e);
        this.status = 4;
        this.text = `最近核销：${fphm}`;
        this.isLog = false;
      }
    },
    inputblur() {
      // FireFox 和 IE 失去焦点，blur直接执行focus 不会生效，加个延时
      setTimeout(() => {
        this.$refs.inputValue?.focus();
        this.scanCode = "";
        console.log(10);
      }, 10);
    },
    getCode() {
      this.status = 1;
      console.log(
        `http://localhost:8081/#/?token=${this.phoneToken}&name=${this.phoneName}&code=${this.phoneCode}&bxr=${this.user}&bxlx=${this.inType}&typeName=${this.phoneType}&mc=${this.mc2Type}&deptId=${this.selectId}`
      );
      const path = `https://yp.h5.cf37.cn/#/?token=${this.phoneToken}&name=${this.phoneName}&code=${this.phoneCode}&bxr=${this.user}&bxlx=${this.inType}&typeName=${this.phoneType}&mc=${this.mc2Type}&deptId=${this.selectId}`;
      const url = encodeURI(path);
      const canvas = document.getElementById("canvas");
      QRCode.toCanvas(canvas, url, {
        width: 180,
        height: 180,
      });
    },
    /** 报销人 */
    getList() {
      listAllInvoiceExpensesUser(this.queryParams).then((response) => {
        this.userList = response.data;
        if (this.userList.length) {
          this.user = this.userList[0].name;
        }
        this.getCode();
      });
    },
    //部门
    getAllList() {
      listAllInvoiceDept({ deptId: this.selectId }).then((response) => {
        this.deptList = response.data;
        if (this.deptList.length) {
          this.queryParams.deptId = response.data[0].id;
          this.dept = response.data[0].id;
        }
        this.getType();
      });
    },
    //类型
    getType() {
      listAllInvoiceExpensesType({ deptId: this.selectId }).then((response) => {
        this.typeList = response.data;
        if (this.typeList.length) {
          this.inType = this.typeList[0].id;
          this.phoneType = this.typeList[0].name;
        }
        this.getList();
      });
    },
    changeDept(val) {
      console.log(val);
      this.queryParams.deptId = val;
      this.user = null;
      this.getList();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["userform"].validate((valid) => {
        if (valid) {
          addInvoiceExpensesUser(this.userform).then((response) => {
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    submitType() {
      this.$refs["typeform"].validate((valid) => {
        if (valid) {
          addInvoiceExpensesType(this.typeform).then((response) => {
            this.$modal.msgSuccess("报销成功");
            this.typeShow = false;
            this.getType();
          });
        }
      });
    },
    showUser() {
      this.userform = {
        name: null,
        deptId: null,
      };
      this.resetForm("userform");
      this.open = true;
    },
    showType() {
      this.typeform = {
        name: null,
      };
      this.resetForm("typeform");
      this.typeShow = true;
    },
    submitAll() {
      if (!this.user) {
        this.$modal.msgError("请选择报销人");
        return;
      }
      if (!this.inType) {
        this.$modal.msgError("请选择报销类型");
        return;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.bxr = this.user;
          this.form.bxlx = this.inType;
          this.form.mc2Type = this.mc2Type;
          this.form.deptId = this.selectId;
          checkUser(this.form)
            .then((response) => {
              this.$modal.msgSuccess("核销成功");
              this.num++;
              this.form = {
                type: null,
                fphm: null,
                hjje: null,
                kprq: null,
                fpdm: null,
                bxlx: null,
                bxr: null,
              };
              this.resetForm("form");
            })
            .catch((err) => {});
        }
      });
    },
    changeType(val) {
      const str = this.typeList.find((item) => item.id === val);
      console.log(str);
      this.phoneType = str.name;
      this.getCode();
    },
    GetDateStr(AddDayCount) {
      var dd = new Date();
      dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
      var y = dd.getFullYear();
      var m = ("0" + (dd.getMonth() + 1)).slice(-2); //获取当前月份的日期
      var d = ("0" + dd.getDate()).slice(-2);
      return y + "年" + m + "月" + d + "日";
    },
  },
};
</script>
<style lang="scss">
.about {
}
.about-input {
  background: #36a7ff;
  width: 100%;
  padding: 2vw 9.4vw;
  box-sizing: border-box;
  display: flex;

  position: relative;
}
.flex-row {
  display: flex;
  align-items: center;
}
.scale {
  margin-top: 2vw;
  padding: 0 9.4vw;
}
.about-atatus {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  .el-input__inner {
    // height: 0;
    // width: 0;
    position: fixed;
    left: -10000px;
  }
}
.input-con {
  position: fixed;
  top: -10000px;
}
.about-fp {
  width: 60vw;
  margin: 0 auto;
  margin-top: 6vw;
}
.sub-but {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 20px;
}
</style>
